<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/31
 * Time: 17:53
 */
namespace C\lib{

    use C\mod\express;

    require LIB_PATH. 'WxpayAPI/lib/WxPay.Config.php';
    class Share{
        public static function getSignPackage() {
            echo 123;
            $jsapiTicket = self::getJsApiTicket();
            //var_dump($jsapiTicket);exit;

            // 注意 URL 一定要动态获取，不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

            $timestamp = time();
            $nonceStr = self::createNonceStr();

            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

            $signature = sha1($string);

            $signPackage = array(
                "appId"     => \WxPayConfig::APPID,
                "nonceStr"  => $nonceStr,
                "timestamp" => $timestamp,
                "url"       => $url,
                "signature" => $signature,
                "rawString" => $string
            );
            return $signPackage;
        }

        private static function createNonceStr($length = 16) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            return $str;
        }

        private static function getJsApiTicket() {
            // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
            $data = json_decode(self::get_php_file(LIB_PATH."radis/jsapi_ticket.php"));
            if ($data->expire_time < time()) {
                $accessToken = self::getAccessToken();
                echo 123;
                var_dump($accessToken);exit();
                // 如果是企业号用以下 URL 获取 ticket
                // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                $res = json_decode(self::httpGet($url));
                $ticket = $res->ticket;
                if ($ticket) {
                    $data->expire_time = time() + 7000;
                    $data->jsapi_ticket = $ticket;
                    self::set_php_file(LIB_PATH."radis/jsapi_ticket.php", json_encode($data));
                }
            } else {
                $ticket = $data->jsapi_ticket;
            }

            return $ticket;
        }
        public static function get($url) {
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $output=curl_exec($ch);
            //var_dump($output);exit;
            curl_close($ch);
            return $output; //exit;
        }
        public static function getAccessToken() {

            // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
            $data = json_decode(self::get_php_file(LIB_PATH."radis/access_token.php"));
            if ($data->expire_time < time()) {
                $appid=\WxPayConfig::APPID;
                $sercret=\WxPayConfig::APPSECRET;
                //bd20170601wxgzh
                //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx08a944d5a385e626&secret=a7c5fb282f444d28647f69657fcb8fe0";
               // echo $url; exit;
                $res = json_decode(self::get($url));
                //var_dump($a); exit;
                $access_token = $res->access_token;
                if ($access_token) {
                    $data->expire_time = time() + 7000;
                    $data->access_token = $access_token;
                    self::set_php_file(LIB_PATH."radis/access_token.php", json_encode($data));
                }
            } else {
                $access_token = $data->access_token;
            }
            return $access_token;
        }

        public static function httpGet($url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
            // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }
        private static function httpPost($url,$data){
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL,$url);
             //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 1);
              //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
              //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
             //执行命令
            $data = curl_exec($curl);
           // var_dump($data);exit;
             //关闭URL请求
            curl_close($curl);
             //显示获得的数据
             return $data;
        }

        private static function get_php_file($filename) {
            return trim(substr(file_get_contents($filename), 15));
        }
        private static function set_php_file($filename, $content) {
            $fp = fopen($filename, "w");
            fwrite($fp, "<?php exit();?>" . $content);
            fclose($fp);
        }
        /*
         * 设置所属行业
         */
        public static function industry(){
            $access_token=self::getAccessToken();
            $data['access_token']=$access_token;
            $data['industry_id1']=2;
            $data['industry_id2']=13;
            $a=json_encode($data);
            $url="https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=".$access_token;
            $data=self::httpPost($url,$a);
            return $data;
        }
        /*
         * 获取设置的行业信息
         */
        public static function getInfo(){
            $access_token=self::getAccessToken();
            //$url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".$access_token;
            $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::get($url);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         * 获取模板号
         */
        public static function gettemid(){
            $access_token=self::getAccessToken();
            $data['access_token']=$access_token;
            $data['template_id_short']='OPENTM201027336';
            $url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".$access_token;
           // $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::httpPost($url);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         *获取模板列表
         */
        public static function temlist(){
            $access_token=self::getAccessToken();

            $url="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".$access_token;
            // $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::get($url);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         * 发送模板消息
         */
        public static function sendInfo($openid){
            $access_token=self::getAccessToken();
            //echo $access_token;exit;
            $v =[
                'touser'=>$openid,
                'template_id'=>'7emhWa94awWuufiP4z1ZPCEAyHeONx8wt0QzpexTGX0',
                'url'=>'http://weixin.qq.com/download',
                'miniprogram' => [
                    'appid'=>'',
                    'pagepath'=>''
                ],
                'data'=>[
                    'first'=>[
                        'value'=>'pppp'
                    ],
                    'keyword1'=>[
                        'value'=>'pppp'
                    ],
                    'keyword2'=>[
                        'value'=>'pppp'
                    ],
                    'keyword3'=>[
                        'value'=>'pppp'
                    ],
                    'remark'=>[
                        'value'=>'pppp'
                    ]
                ]
            ];
            $c=json_encode($v);
            //var_dump($c);exit();

            $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
            // $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::httpPost($url,$c);

            var_dump($data);
        }
    }
}
